package src.utils;
import org.w3c.dom.Document;
import javax.xml.XMLConstants;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.Validator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.InputStream;

public class XMLValidator {
	
	

	public static void validate(String xmlFile, String schemaFile) throws Exception {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document document = parser.parse(new File(xmlFile));
		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Source schemaSource= new StreamSource(new File(schemaFile));
		Schema schema = factory.newSchema(schemaSource);
		Validator validator = schema.newValidator();
		validator.validate(new DOMSource(document));
	}


	public static void validate(Document inDoc, Source inSource) throws Exception {
		
		Document document = inDoc;
		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		
	
		Source schemaSource= inSource;
		Schema schema = factory.newSchema(schemaSource);
		Validator validator = schema.newValidator();
		validator.validate(new DOMSource(document));
	}
	
	public static void validate(InputStream inStream, Source inSource) throws Exception {
		
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inStream);
		SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		
	
		Source schemaSource= inSource;
		Schema schema = factory.newSchema(schemaSource);
		Validator validator = schema.newValidator();
		validator.validate(new DOMSource(document));
	}

	public static void main(String[] args) {
		if (args.length != 2){
			System.err.println("Usage: cmd xmlfile schemafile");
			System.exit(1);
		}
		try {
			XMLValidator.validate(args[0],args[1]);
		}catch(Exception ex) {
			System.out.println(ex.getMessage());
			System.err.println("Your document: "+ args[0] + " is not valid against: "+args[1]);
		}
	}
}